#!/usr/bin/python2.4


from AbstractExtractor import *
import Image
from tools.writer import *
from tools.pygooglechart import *
from tools.pygooglechart.pygooglechart import Axis

class histogramCondensed(AbstractExtractor):
  def __init__(self, image_path, bucketSize = 8):
    	self.image_path = image_path
	self.writer = basicWriter.basicWriter()
	self.bucketSize = bucketSize

  def run(self):
	im = Image.open(self.image_path)
	self.histogram = im.histogram()

  def resultshort(self):
	return ""

  def resultlong(self):
        self.writer.addFunction('Histogram')
	self.writer.addSubset('Red')
	i = 0
	currSum = 0
	maxValue = 0
	size = len(self.histogram)
	for point in self.histogram:
		currSum += point
		#Keep track of max value
		if point > maxValue:
			maxValue = point
		#Add value to subset at end of bucket
		if (i % self.bucketSize == self.bucketSize - 1):
			self.writer.addValue(currSum)
			currSum = 0
		#Change subsets at 1/3 and 2/3 through
		if (i == size / 3):
			self.writer.addSubset('Green')
		elif (i == 2 * size / 3):
			self.writer.addSubset('Blue')
		i += 1;

	subsets = self.writer.getSubsets()
	chart = pygooglechart.SimpleLineChart(300, 200)

	chart.set_legend(('Red', 'Green', 'Blue'))
	# Add the data
	for eachSubset in subsets:
		chart.add_data(eachSubset[1])
	# Fix the data colors (colours)
	chart.set_colours(('FF0000','00FF00','0000FF'))
	
	# Add axis labels to the chart
	index = chart.set_axis_range(Axis.BOTTOM, 0, 255)
	chart.set_axis_style(index, colour='777777')
	# X axis label centered and blue
	index = chart.set_axis_labels(Axis.BOTTOM, ['Bin Number'])
	chart.set_axis_style(index, colour='0000FF', alignment=0)

	index = chart.set_axis_range(Axis.LEFT, 0, maxValue)
	chart.set_axis_style(index, colour='777777')
	#Y axis label blue and positioned
	index = chart.set_axis_labels(Axis.LEFT, ['Count', 'Bucket'])
	chart.set_axis_style(index, colour='0000FF')
	chart.set_axis_positions(index, [40, 60])
	
	# We don't want the full URL, just the important parts
	url_bits = chart.get_url_bits()
        return "Histogram: " + '&'.join(url_bits)

